package Algorithms.five.fenzhi;

/**
 * description: 找一个序列的最大子序列<br>
 * createTime: 2020/12/30 15:46 <br>
 *
 * @author zzh
 */
public class FIndMaxSubSeq {
    public static void main(String[] args) {
        int[] a = { -2, 11, -4, 13, -5, -2 };// 最大子序列和为20
        int[] b = { -6, 2, 4, -7, 5, 3, 2, -1, 6, -9, 10, -2 };// 最大子序列和为16
        int[] c = { -6, -4, -5, -1, -2, -3};
        System.out.println(maxSubSum1(a));
        System.out.println(maxSubSum1(b));
        System.out.println(maxSubSum1(c));
        System.out.println("---------------------------");
        System.out.println(maxSubSum3(a));
        System.out.println(maxSubSum3(b));
        System.out.println(maxSubSum3(c));
        System.out.println("---------------------------");
        System.out.println(maxSubSum4(a));
        System.out.println(maxSubSum4(b));
        System.out.println(maxSubSum4(c));
    }

    //循环实现
    private static int maxSubSum1(int[] a) {
        int maxSum = Integer.MIN_VALUE;
        for (int i = 0; i < a.length; i++) {
            int sum  = 0;
            for (int j = i; j < a.length; j++) {
                sum += a[j];
                if(sum >= maxSum) {
                    maxSum = sum;
                }
            }
        }
        return maxSum;
    }

    // 递归，分治策略
// 2分logn，for循环n，时间复杂度O(nlogn)
    public static int maxSubSum3(int[] a) {
        return maxSumRec(a, 0, a.length - 1);
    }

    public static int maxSumRec(int[] a, int left, int right) {
        // 递归中的基本情况
        if (left == right) {
            if (a[left] > 0)
                return a[left];
            else
                return 0;
        }
        int center = (left + right) / 2;
        // 最大子序列在左侧
        int maxLeftSum = maxSumRec(a, left, center);
        // 最大子序列在右侧
        int maxRightSum = maxSumRec(a, center + 1, right);
        // 最大子序列在中间（左边靠近中间的最大子序列+右边靠近中间的最大子序列）
        int maxLeftBorderSum = 0, leftBorderSum = 0;
        for (int i = center; i >= left; i--) {
            leftBorderSum += a[i];
            if (leftBorderSum > maxLeftBorderSum)
                maxLeftBorderSum = leftBorderSum;
        }
        int maxRightBorderSum = 0, rightBorderSum = 0;
        for (int i = center + 1; i <= right; i++) {
            rightBorderSum += a[i];
            if (rightBorderSum > maxRightBorderSum)
                maxRightBorderSum = rightBorderSum;
        }
        // 返回最大子序列在左侧，在右侧，在中间求出的值中的最大的
        return max3(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);
    }

    public static int max3(int a, int b, int c) {
        return a > b ? (a > c ? a : c) : (b > c ? b : c);
    }

    public static int maxSubSum4(int[] a) {
        int maxSum = Integer.MIN_VALUE, thisSum = 0;
        for (int j = 0; j < a.length; j++) {
            thisSum += a[j];
            if (thisSum > maxSum)
                maxSum = thisSum;
            if (thisSum < 0)
                thisSum = 0;
        }
        return maxSum;
    }
}
